import { useCallback, useEffect, useRef } from "react"
import { DeviceEventEmitter } from "react-native";

// 事件监听
const useListen = () => {
    const ref = useRef({ eventList: [] })

    const addListen = useCallback((eventName, callBack) => {
        ref.current.eventList?.[eventName]?.remove()
        ref.current.eventList[eventName] = DeviceEventEmitter.addListener(eventName, callBack)
    }, [])

    useEffect(() => {
        return () => {
            const { eventList } = ref.current
            for (const key of eventList) {
                eventList[key]?.remove()
            }
        }
    }, [])
    return [ref.current, addListen]
}

export default useListen